import logging
import os
import time

class infoFilter(logging.Filter):
    def filter(self,record):
        return record.levelno==logging.INFO

class errFilter(logging.Filter):
    def filter(self,record):
        return record.levelno==logging.ERROR

class logger:
    #读取日志对象,定义类方法,相当于java的静态方法
    @classmethod
    def getlog(cls):
        #创建类的日志对象
        #__name__ 使用模块名
        cls.logger = logging.getLogger(__name__)
        cls.logger.setLevel(logging.DEBUG)

        #将日志输出到日志文件中
        #按照日期和级别分割日志
        '''
        2025-01-01.log 
        2025-01-01-debug.log 
        2025-01-01-info.log 
        '''


        log_path = './logs/'
        if not os.path.exists(log_path) :
             os.mkdir(log_path)

        now = time.strftime("%Y-%m-%d")
        log_name = log_path + now + ".log"
        info_log_name = log_path + now + "-info.log"
        err_log_name = log_path + now + "-err.log"

        #创建日志文件处理
        all_handle = logging.FileHandler(log_name,encoding='utf-8')
        info_log_handle = logging.FileHandler(info_log_name,encoding='utf-8')
        err_log_handle = logging.FileHandler(err_log_name,encoding='utf-8')

        #设置日志的格式
        #                              时间戳         日志等级      日志对象的模块名 写入日志的方法  具体的行数     打印的信息
        formatter = logging.Formatter("%(asctime)s %(levelname)s [%(name)s] [%(filename)s:%(lineno)d] - %(message)s")

        all_handle.setFormatter(formatter)
        info_log_handle.setFormatter(formatter)
        err_log_handle.setFormatter(formatter)

        info_log_handle.addFilter(infoFilter())
        err_log_handle.addFilter(errFilter())

        cls.logger.addHandler(all_handle)
        cls.logger.addHandler(info_log_handle)
        cls.logger.addHandler(err_log_handle)

        return cls.logger


